﻿namespace ASB.CC.Web.EZVisit.Report
{
    #region Using Directives

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using ASBCC.Workflow.Client;
    using BEGDC.Utility.Extensions;

    #endregion

    public partial class EZVisitDashboardPrint : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                string condition = this.Request.QueryString["sn"];

                if (condition.IsNotNullOrWhiteSpace())
                {
                    this.Search(Decode(condition));
                }
            }
        }

        private static string Decode(string originalString)
        {
            string output = string.Empty;

            try
            {
                byte[] bytes = Convert.FromBase64String(originalString);
                output = Encoding.Default.GetString(bytes);
            }
            catch
            {
            }

            return output;
        }

        private void Search(string condition)
        {
            var parameters = condition.Split('|');

            if (parameters.Length != 9)
            {
                return;
            }

            DateTime month1;

            DateTime month2;

            if (!DateTime.TryParse(parameters[0], out month1) || !DateTime.TryParse(parameters[1], out month2) || month2 < month1)
            {
                this.lblOutput.Text = string.Empty;
                return;
            }

            this.lblStartDate.Text = month1.ToString("yyyy.MM");
            this.lblEndDate.Text = month2.ToString("yyyy.MM");
            this.lblStatus.Text = this.Server.HtmlEncode(parameters[3]);
            this.lblCustomer.Text = this.Server.HtmlEncode(parameters[5]);
            this.lblCODPPCheckPerson.Text = this.Server.HtmlEncode(parameters[8]);

            var cmdText = new StringBuilder();

            cmdText.AppendFormat(@"IsEnabled = 1 and SubmitDate is not null and ((RequestedDateFrom >= '{0}' and RequestedDateFrom < '{1}') or ( RequestedDateTo >= '{0}' and RequestedDateTo < '{1}') or ( RequestedDateFrom <= '{0}' and RequestedDateTo >= '{1}') or ( RequestedDateFrom >= '{0}' and RequestedDateTo < '{1}'))", month1, month2.AddMonths(1));

            string status = parameters[2].SanitizeSqlValue();

            switch (status)
            {
                case "Draft":
                    cmdText.Append(" and (Status is null or Status = '')");
                    break;
                case "LGDApproved":
                    cmdText.AppendFormat(" and LGDDate is not null and ProcessStatus <> '{0}'", ProcessStatusConsts.End);
                    break;
                case "In Process":
                    string filter = string.Format("'{0}', '{1}'", ProcessStatusConsts.Discarded, ProcessStatusConsts.End);
                    cmdText.AppendFormat(" and LGDDate is null and ProcessStatus not in ({0})", filter);
                    break;
                case "Approved":
                    cmdText.AppendFormat(" and ProcessStatus = '{0}'", ProcessStatusConsts.End);
                    break;
                case "Rejected":
                    cmdText.AppendFormat(" and ProcessStatus = '{0}'", ProcessStatusConsts.Rejected);
                    break;
                case "Discarded":
                    cmdText.AppendFormat(" and ProcessStatus = '{0}'", ProcessStatusConsts.Discarded);
                    break;
            }

            if (!parameters[4].VariantEquals("all"))
            {
                cmdText.AppendFormat(" and DepartmentName = {0}", parameters[4].SanitizeSqlValue());
            }

            if (!parameters[7].VariantEquals("all"))
            {
                cmdText.AppendFormat(" and Region = '{0}'", parameters[7].SanitizeSqlValue());
            }

            if (!string.IsNullOrEmpty(parameters[5]))
            {
                 cmdText.AppendFormat(" and Company like '%{0}%'", parameters[5].SanitizeSqlValue());
            }

            if (!parameters[6].VariantEquals("all"))
            {
                cmdText.AppendFormat(" and (CODPPCheckPersonID ={0})", parameters[6].SanitizeSqlValue());
            }

            EZVisitApplicationTableEntitySet applications = EZVisitApplicationManager.SelectByCondition(cmdText.ToString());

            if (applications.Count > 0)
            {
                var monthes = new List<string>();

                while (month1.Year < month2.Year)
                {
                    //从起始月加到同年12月
                    for (int i = month1.Month; i <= 12; i++)
                    {
                        monthes.Add(month1.Year + "-" + i);
                    }

                    month1 = new DateTime(month1.Year + 1, 1, 1);
                }

                if (month1.Year == month2.Year)
                {
                    //加到同年截止月份
                    for (int i = month1.Month; i <= month2.Month; i++)
                    {
                        monthes.Add(month2.Year + "-" + i);
                    }
                }

                this.lblOutput.Text = this.CreateDashboard(applications, monthes);
            }
        }

        private string CreateDashboard(EZVisitApplicationTableEntitySet applications, IList<string> monthes)
        {
            const int tableWidth = 950;
            const int titleWidth = 60;

            int mainWidth = tableWidth - titleWidth - 8*monthes.Count;
            int monthWidth = mainWidth/monthes.Count;

            int wcell = monthWidth + 2;
            int hcell = wcell/2;

            var statusColors = new Hashtable();

            foreach (ListItem item in this.ddlStatusColor.Items)
            {
                statusColors.Add(item.Value, item.Text);
            }

            var op = new StringBuilder();

            //
            // 背景，时间轴表单队列
            //
            op.Append("<div class='dashboard-body'>");

            op.Append(string.Format("<table width='{0}'>", tableWidth));

            for (int i = 0; i < applications.Count; i++)
            {
                var bcell = new StringBuilder();

                // month cell
                foreach (string t in monthes)
                {
                    bcell.AppendFormat(@"<td class='dashboard-y-line' width='{0}'></td>", monthWidth);
                }

                // body
                op.AppendFormat(@"<tr><td width='{0}' class='dashboard-y'></td>{1}<td ></td></tr>", titleWidth, bcell);
            }

            // X轴
            op.AppendFormat(@"<tr><td></td><td class='dashboard-x' colspan='{0}'></td><td class='dashboard-x'></td></tr>", monthes.Count);

            // X轴点
            op.Append(@"<tr><td></td>");

            foreach (string t in monthes)
            {
                op.AppendFormat(@"<td width='{0}' class='dashboard-x-line'>&nbsp;</td>", monthWidth);
            }

            op.Append(@"<td></td></tr></table>");

            //
            // X轴点下的年月份
            //
            op.AppendFormat(@"<table width='{0}'><tr><td>&nbsp;</td>", tableWidth);

            for (int i = 0; i < monthes.Count; i++)
            {
                int w = i == 0 ? monthWidth + 1 : monthWidth + 2;
                op.AppendFormat(@"<td width='{0}' class='ac'>{1}</td>", w, monthes[i]);
            }

            op.Append(@"<td>&nbsp;</td></tr></table></div>");

            //
            // 前景，访问日期段条
            //
            op.AppendFormat(@"<div id='pencil' class='dashboard-body'><table width={0}>", tableWidth);

            foreach (EZVisitApplicationTableEntity app in applications)
            {
                int lineStart = 0;
                int lineEnd = 0;

                if (app.RequestedDateFrom != null && app.RequestedDateTo != null && app.RequestedDateTo.Value >= app.RequestedDateFrom.Value)
                {
                    var startDate = app.RequestedDateFrom.Value;
                    var endDate = app.RequestedDateTo.Value;

                    int startIndex = monthes.IndexOf(startDate.Year + "-" + startDate.Month);
                    int endIndex = monthes.IndexOf(endDate.Year + "-" + endDate.Month);

                    if (startIndex != -1)
                    {
                        int c = startDate.Day/7;

                        lineStart = wcell*startIndex + (c == 0 ? 0 : wcell*c/4);
                    }

                    if (endIndex != -1)
                    {
                        var c = (int) Math.Round(endDate.Day/7.0);

                        lineEnd = wcell*endIndex + (c == 0 ? 0 : wcell*c/4);
                    }

                    if ((endDate - startDate).Days < 3)
                    {
                        lineStart = lineEnd - 3;
                    }

                    op.AppendFormat(@"<tr><td width='{0}' height='36'  class='ar'>{1}&nbsp;&nbsp;</td>", titleWidth + 1, app.EZVisitReqNo);

                    string step = app.CurrentStep;

                    if (step == null)
                    {
                        step = "Draft";
                    }
                    else if (step.Length == 0)
                    {
                        step = "Closed";
                    }

                    string title = string.Format(@"Application No.: {0}
Requested Date of visit: {1} to {2}
Current Step: {3}
Current Approver: {4}
", app.EZVisitReqNo, startDate.ToShortDateString(), endDate.ToShortDateString(), step,
                                                 app.CurrentApprover);

                    string color = statusColors.ContainsKey(step) ? statusColors[step] + "" : "#666";

                    op.AppendFormat(@"<td><a href='../EZVRequest.aspx?id={0}' target='_blank' title='{1}'><div title='{1}' style=' height: 2em; background-color: {2}; margin-left: {3}px; width: {4}px;'></div></a></td></tr>", app.AppID, title, color,
                                    lineStart, lineEnd - lineStart);
                }
            }

            op.Append("</table></div>");

            DateTime today = DateTime.Today;
            int todayidx = monthes.IndexOf(today.Year + "-" + today.Month);
            if (todayidx != -1)
            {
                int todayMargin;
                if (today.Day <= 9)
                {
                    todayMargin = hcell/2;
                }
                else if (today.Day <= 15)
                {
                    todayMargin = hcell;
                }
                else if (today.Day <= 24)
                {
                    todayMargin = hcell/2 + hcell;
                }
                else
                {
                    todayMargin = wcell;
                }

                op.Append(string.Format(@"<div style='position:absolute; border-left:1px dashed #aaa; height:{0}px; top:20px; left:{1}px;'>", 36*applications.Count, titleWidth + wcell*todayidx + todayMargin));
            }

            return op.ToString();
        }
    }
}